<template>
	<a-card :bordered="false">
		<a-form ref="searchFormRef" name="advanced_search" :model="searchFormState" class="ant-advanced-search-form mb-4">
			<a-row :gutter="24">
				<a-col :span="6">
					<a-form-item label="姓名/学工号" name="userName">
						<a-input v-model:value.trim="searchFormState.userName" placeholder="请输入姓名/学工号" allow-clear />
					</a-form-item>
				</a-col>
				<a-col :span="6">
					<a-form-item label="状态" name="permState">
						<a-select
							v-model:value="searchFormState.permState"
							placeholder="请选择状态"
							:options="permStateOptions"
							allow-clear
						/>
					</a-form-item>
				</a-col>
				<a-col :span="6">
					<a-form-item label="授权类型" name="deviceType">
						<a-select
							v-model:value="searchFormState.deviceType"
							placeholder="请选择授权类型"
							:options="deviceTypeOptions"
							allow-clear
						/>
					</a-form-item>
				</a-col>
				<template v-if="advanced">
					<a-col :span="6">
						<a-form-item label="组柜/柜子/柜门" name="deviceName">
							<a-input v-model:value.trim="searchFormState.deviceName" placeholder="请输入名称" allow-clear />
						</a-form-item>
					</a-col>
				</template>
				<a-col :span="6">
					<a-button type="primary" @click="table.clearRefreshSelected(true)">查询</a-button>
					<a-button style="margin: 0 8px" @click="resetForm">重置</a-button>
					<a @click="toggleAdvanced" style="margin-left: 8px">
						{{ advanced ? '收起' : '展开' }}
						<component :is="advanced ? 'up-outlined' : 'down-outlined'" />
					</a>
				</a-col>
				<a-col :span="6">
					<a-form-item label="组柜ID" name="cabinetGroupId" hidden>
						<a-input v-model:value.trim="searchFormState.cabinetGroupId" />
					</a-form-item>
				</a-col>
				<a-col :span="6">
					<a-form-item label="柜子ID" name="cabinetInfoId" hidden>
						<a-input v-model:value.trim="searchFormState.cabinetInfoId" />
					</a-form-item>
				</a-col>
				<a-col :span="6">
					<a-form-item label="柜门ID" name="cabinetDoorId" hidden>
						<a-input v-model:value.trim="searchFormState.cabinetDoorId" />
					</a-form-item>
				</a-col>
			</a-row>
		</a-form>
		<s-table
			ref="table"
			:columns="columns"
			:data="loadData"
			:alert="options.alert.show"
			bordered
			:row-key="(record) => record.id"
			:tool-config="toolConfig"
			:row-selection="options.rowSelection"
		>
			<template #operator class="table-operator">
				<a-space>
					<a-button type="primary" @click="batchAuthorizeUsersRef.onOpen()">选择用户授权</a-button>
					<a-button type="primary" @click="batchFreezeUsersRef.onOpen()">选择用户冻结</a-button>
					<a-popconfirm :title="batchAuthorizeTips" @confirm="batchAuthorize">
						<a-button type="primary">批量授权</a-button>
					</a-popconfirm>
					<a-popconfirm :title="batchRefuseTips" @confirm="batchRefuse">
						<a-button type="primary">批量拒绝</a-button>
					</a-popconfirm>
				</a-space>
			</template>
			<template #bodyCell="{ column, record }">
				<template v-if="column.dataIndex === 'fullName'">
					{{ record.cabinetGroupName }} {{ record.cabinetInfoName }} {{ record.cabinetDoorName }}
				</template>
				<template v-if="column.dataIndex === 'permTimeRange'">
					<div>{{ record.permStartTime }}</div>
					<div>{{ record.permEndTime }}</div>
				</template>
				<template v-if="column.dataIndex === 'frozenTimeRange'">
					<div>{{ record.frozenStartTime }}</div>
					<div>{{ record.frozenEndTime }}</div>
				</template>
				<template v-if="column.dataIndex === 'permState'">
					{{ permStateOptions.filter((item) => item.value === record.permState)[0].label }}
				</template>
				<template v-if="column.dataIndex === 'deviceType'">
					{{ deviceTypeOptions.filter((item) => item.value === record.deviceType)[0].label }}
				</template>
				<template v-if="column.dataIndex === 'detail'">
					<template v-if="record.permState === 'UNAUTHORIZED'">
						<div><a @click="certificationRef.onOpen(record)">查看证书</a></div>
						<div><a @click="permLogRef.onOpen(record, true)">历史申请</a></div>
					</template>
				</template>
				<template v-if="column.dataIndex === 'action'">
					<div>
						<a-space>
							<a @click="authorizeRef.onOpen(record)" v-if="record.permState === 'UNAUTHORIZED'">授权</a>
							<a @click="refuseRef.onOpen(record)" v-if="record.permState === 'UNAUTHORIZED'">拒绝</a>
						</a-space>
					</div>
					<div>
						<a-space>
							<a
								@click="frozenRef.onOpen(record)"
								v-if="['UNAUTHORIZED', 'AUTHORIZED'].find((item) => item === record.permState)"
								>冻结</a
							>
							<a-popconfirm
								title="确定要解冻吗？"
								@confirm="unFreezeCabinetPermission(record)"
								v-if="record.permState === 'FROZEN'"
							>
								<a>解冻</a>
							</a-popconfirm>
							<a @click="permLogRef.onOpen(record, false)">日志</a>
						</a-space>
					</div>
				</template>
			</template>
		</s-table>
	</a-card>
	<Authorize ref="authorizeRef" @successful="table.refresh(false)" />
	<Frozen ref="frozenRef" @successful="table.refresh(false)" />
	<Refuse ref="refuseRef" @successful="table.refresh(false)" />
	<BatchAuthorizeUsersRef ref="batchAuthorizeUsersRef" @successful="table.refresh(false)" />
	<BatchFreezeUsers ref="batchFreezeUsersRef" @successful="table.refresh(false)" />
	<BatchAuthorize ref="batchAuthorizeRef" @successful="table.refresh(false)" />
	<BatchRefuse ref="batchRefuseRef" @successful="table.refresh(false)" />
	<PermissionLog ref="permLogRef" @successful="table.refresh(false)" />
	<Certification ref="certificationRef" />
</template>

<script setup name="cabinetpermission">
	import { message } from 'ant-design-vue'
	import tool from '@/utils/tool'
	import { watchEffect } from 'vue'
	import Authorize from './authorize.vue'
	import BatchAuthorize from './batchAuthorize.vue'
	import Frozen from './frozen.vue'
	import Refuse from './refuse.vue'
	import BatchAuthorizeUsersRef from './batchAuthorizeUsers.vue'
	import BatchFreezeUsers from './batchFreezeUsers.vue'
	import BatchRefuse from './batchRefuse.vue'
	import PermissionLog from '../cabinetpermissionlog/index.vue'
	import Certification from './certification.vue'
	import bizCabinetPermissionReagentApi from '@/api/biz/bizCabinetPermissionReagentApi'
	import { useRouter } from 'vue-router'

	const searchFormState = reactive({})
	const searchFormRef = ref({})
	const table = ref()
	const formRef = ref()
	const authorizeRef = ref()
	const frozenRef = ref()
	const refuseRef = ref()
	const batchAuthorizeUsersRef = ref()
	const batchFreezeUsersRef = ref()
	const batchAuthorizeRef = ref()
	const batchRefuseRef = ref()
	const permLogRef = ref()
	const certificationRef = ref()
	const toolConfig = { refresh: true, height: true, columnSetting: true, striped: false }
	// 查询区域显示更多控制
	const advanced = ref(false)
	const loadParamFromRoute = ref(false)
	const noBatchOperation = ref(false) // 是否可以批量操作
	const batchRefuseTips = ref('没有需要操作的记录')
	const batchAuthorizeTips = ref('没有需要操作的记录')
	const toggleAdvanced = () => {
		advanced.value = !advanced.value
	}
	const columns = [
		{
			title: '学工号',
			dataIndex: 'account'
		},
		{
			title: '姓名',
			dataIndex: 'userName'
		},
		{
			title: '授权类型',
			dataIndex: 'deviceType',
			width: '75px'
		},
		{
			title: '组柜/柜子/柜门',
			dataIndex: 'fullName'
		},
		{
			title: '申请时间',
			dataIndex: 'userApplyTime',
			width: '90px'
		},
		{
			title: '申请天数',
			dataIndex: 'userApplyDays',
			width: '75px'
		},
		{
			title: '权限起止时间',
			dataIndex: 'permTimeRange',
			width: '145px'
		},
		{
			title: '冻结起止时间',
			dataIndex: 'frozenTimeRange',
			width: '145px'
		},
		{
			title: '授权天数',
			dataIndex: 'permDays',
			width: '75px'
		},
		{
			title: '剩余天数',
			dataIndex: 'remainDays',
			width: '75px'
		},
		{
			title: '状态',
			dataIndex: 'permState',
			width: '70px'
		},
		{
			title: '详情',
			dataIndex: 'detail',
			width: '80px'
		}
	]
	// 操作栏通过权限判断是否显示
	if (hasPerm(['bizCabinetPermissionReagentEdit', 'bizCabinetPermissionReagentDelete'])) {
		columns.push({
			title: '操作',
			dataIndex: 'action',
			align: 'center',
			width: '100px'
		})
	}
	let selectedRowKeys = ref([])
	// 列表选择配置
	const options = {
		alert: {
			show: false,
			clear: () => {
				selectedRowKeys = ref([])
			}
		},
		rowSelection: {
			onChange: (selectedRowKey, selectedRows) => {
				noBatchOperation.value = false
				selectedRowKeys.value = selectedRowKey
				// console.log(selectedRows)
				let toBeAuthCount = selectedRows.filter((row) => row.permState === 'UNAUTHORIZED').length
				// console.log(selectedRows)

				if (toBeAuthCount === 0) {
					noBatchOperation.value = true
					return
				}

				let distinctApplyDays = new Set(selectedRows.map((row) => row.userApplyDays)).size
				console.log('distinctApplyDays=', distinctApplyDays)
				if (distinctApplyDays > 1) {
					let skipTips = `申请天数不一致，无法批量操作`
					batchAuthorizeTips.value = skipTips
					batchRefuseTips.value = skipTips
					noBatchOperation.value = true
					return
				}

				let frozenCount = selectedRows.filter((row) => row.permState === 'FROZEN').length
				let expiredCount = selectedRows.filter((row) => row.permState === 'EXPIRED').length
				let authorizedCount = selectedRows.filter((row) => row.permState === 'AUTHORIZED').length
				let skipTips = `，并跳过对已冻结：${frozenCount}条，已过期：${expiredCount}条，已授权：${authorizedCount}条 记录进行处理？`
				batchAuthorizeTips.value = `请确认是否对 待授权：${toBeAuthCount}条 申请进行授权${skipTips}`
				batchRefuseTips.value = `请确认是否对 待授权：${toBeAuthCount}条 申请进行拒绝${skipTips}`
			}
		}
	}
	const loadData = (parameter) => {
		const searchFormParam = JSON.parse(JSON.stringify(searchFormState))
		return bizCabinetPermissionReagentApi.bizCabinetPermissionPage(Object.assign(parameter, searchFormParam)).then((data) => {
			return data
		})
	}
	// 解冻
	const unFreezeCabinetPermission = (record) => {
		bizCabinetPermissionReagentApi.bizCabinetPermissionUnfreeze(record).then(() => {
			message.success('解冻成功')
			table.value.clearRefreshSelected()
		})
	}
	const permStateOptions = [
		{
			label: '待授权',
			value: 'UNAUTHORIZED'
		},
		{
			label: '已拒绝',
			value: 'REFUSED'
		},
		{
			label: '已授权',
			value: 'AUTHORIZED'
		},
		{
			label: '已冻结',
			value: 'FROZEN'
		},
		{
			label: '已过期',
			value: 'EXPIRED'
		}
	]
	const deviceTypeOptions = [
		{
			label: '组柜',
			value: 'CABINET_GROUP'
		},
		{
			label: '柜子',
			value: 'CABINET_INFO'
		},
		{
			label: '柜门',
			value: 'CABINET_DOOR'
		}
	]
	const batchAuthorize = () => {
		if (selectedRowKeys.value.length < 1) {
			message.warning('请选择一条或多条数据')
			return false
		}
		if (noBatchOperation.value === true) {
			message.warning('不满足条件，无法批量操作')
			return false
		}
		const ids = selectedRowKeys.value
		batchAuthorizeRef.value.onOpen(ids)
		table.value.clearRefreshSelected()
	}
	const batchRefuse = () => {
		if (selectedRowKeys.value.length < 1) {
			message.warning('请选择一条或多条数据')
			return false
		}
		if (noBatchOperation.value === true) {
			message.warning('不满足条件，无法批量操作')
			return false
		}
		const ids = selectedRowKeys.value
		batchRefuseRef.value.onOpen(ids)
		table.value.clearRefreshSelected()
	}

	const router = useRouter()
	watch(
		() => router.currentRoute.value,
		(newValue, oldValue) => {
			if (newValue.name === 'cabinetpermission_reagent') {
				console.log('watch', newValue.params)
				let params = newValue.params
				// 接收路由参数
				let cabinetGroupId = params.cabinetGroupId
				let cabinetGroupName = params.cabinetGroupName
				if (cabinetGroupId && cabinetGroupId !== searchFormState.cabinetGroupId) {
					searchFormState.cabinetGroupId = cabinetGroupId
					searchFormState.cabinetInfoId = null
					searchFormState.cabinetDoorId = null
					searchFormState.deviceType = 'CABINET_GROUP'
					searchFormState.deviceName = cabinetGroupName
					// 加载数据
					if (table.value) {
						table.value.refresh(true)
					}
				}

				let cabinetId = params.cabinetId
				let cabinetName = params.cabinetName
				if (cabinetId && cabinetId !== searchFormState.cabinetInfoId) {
					searchFormState.cabinetGroupId = null
					searchFormState.cabinetInfoId = cabinetId
					searchFormState.cabinetDoorId = null
					searchFormState.deviceType = 'CABINET_INFO'
					searchFormState.deviceName = cabinetName
					// 加载数据
					if (table.value) {
						table.value.refresh(true)
					}
				}

				let cabinetDoorId = params.cabinetDoorId
				let cabinetDoorName = params.cabinetDoorName
				if (cabinetDoorId && cabinetDoorId !== searchFormState.cabinetDoorId) {
					searchFormState.cabinetGroupId = null
					searchFormState.cabinetInfoId = null
					searchFormState.cabinetDoorId = cabinetDoorId
					searchFormState.deviceType = 'CABINET_DOOR'
					searchFormState.deviceName = cabinetDoorName
					// 加载数据
					if (table.value) {
						table.value.refresh(true)
					}
				}
			}
		},
		{
			immediate: true
		}
	)

	const resetForm = () => {
		searchFormRef.value.resetFields()
		searchFormState.cabinetGroupId = null
		searchFormState.cabinetInfoId = null
		searchFormState.cabinetDoorId = null
		searchFormState.deviceType = null
		searchFormState.deviceName = null
		table.value.clearRefreshSelected(true)
	}
</script>
